import axios from 'axios'
import config from '../config/config'
// import store from 'store'
import router from '../router'
// import xlsx from 'xlsx'
import dayjs from 'dayjs'
import { get } from 'lodash-es'
import { warning } from '@/utils/message'
import { ElLoading } from 'element-plus'
// const md5 = require('')


const TOKENNAME = 'tjs_qy_token';
const USERINFO = 'comInfo';
let serviceLoading = null;
// 是否显示token过期提示
let showLogoutMsg = true;

class Http {
  request
  static instance
  timeout = 30000
  ignore = ['/login']

  static getInstance(param) {
    return new Http(param)
  }

  constructor(param) {
    this.request = axios.create({
      baseURL: param.baseURL,
      timeout: param.timeout ?? this.timeout
    })
    this.setResponse()
    this.setRequest()
  }

  static errorMessage(msg = '') {
    warning(msg)
  }

  setResponse() {
    this.request.interceptors.response.use(
      (response) => {
        // serviceLoading.close()
        const data = response.data
        if (response.data instanceof window.Blob) {
          return data
        }
        if (data.code !== 200) {
          const message = get(response, 'data.msg', '系统繁忙，请联系管理员...')
          Http.errorMessage(message)
          return Promise.reject(data)
        }
        return Promise.resolve(data)
      },
      (error) => {
        // serviceLoading.close()
        if (error.code === 'ECONNABORTED' && error.message.includes('timeout')) {
          Http.errorMessage('请求超时')
        }
        const response = error.response
        // showLogoutMsg为避免弹出多个token过期警告
        if (response && response.status === 401 && showLogoutMsg) {
          showLogoutMsg = false
          logout()
          setTimeout(() => {
            showLogoutMsg = true
          }, 3000)
        }

        const message = get(response, 'data.msg', 'servcie error')
        Http.errorMessage(message)
        return Promise.reject(message)
      }
    )
  }

  setRequest() {
    // console.log(config.url)
    // const apiUrl = config.apiUrl
    // this.request.interceptors.request.use(
    //   (config) => {
    //     serviceLoading = setLoading()
    //     let key = 'F5760F840383FE7B' + dayjs().format('YYYYMMDDHHmm')
    //     key += new URL(apiUrl + config.url).pathname.split('/').pop()
    //     const ignoreStat = this.ignore.some((v) => {
    //       return config.url.includes(v)
    //     })
    //     // 判断请求头的url是否为注册和使用单位，是就跳过
    //     if (!ignoreStat && config.url !== '/api/baseSysUser' && config.url !== '/api/companyInfo/getList') {
    //       config.headers.Authorization = getToken()
    //     }
    //     config.headers.m = md5(key).slice(0, 6)
    //     return config
    //   },
    //   (error) => {
    //     return Promise.reject(error)
    //   }
    // )
  }

  // get<T>(url: string, params = {}, extend = {}): Promise<{ [key: string]: any; data?: T }> {
  get(url, params = {}, extend = {}) {
    return this.request({
      method: 'get',
      url,
      params,
      ...extend
    })
  }

  post(url, data = {}, params = {}, extend = {}) {
    return this.request({
      method: 'post',
      url,
      data,
      params,
      ...extend
    })
  }

  postFormData(url, data = {}, params = {}, extend = {}) {
    return this.request({
      method: 'post',
      headers: { 'Content-Type': 'multipart/form-data' },
      url,
      data,
      params,
      ...extend
    })
  }

  delete(url, params = {}, extend = {}) {
    return this.request({
      method: 'delete',
      url,
      params,
      ...extend
    })
  }

  put(url, data = {}, params = {}, extend = {}) {
    return this.request({
      method: 'put',
      url,
      params,
      data,
      ...extend
    })
  }

  /**
   * excel转table
   * @param url
   * @param elem
   */
  //   excelToTableByUrl(url, elem = '') {
  //     return new Promise((resolve) => {
  //       axios(url, { responseType: 'arraybuffer' }).then(function (res) {
  //         const data = new Uint8Array(res.data)
  //         const wb = xlsx.read(data, { type: 'array' })
  //         let html = ''
  //         if (wb.SheetNames.length === 1) {
  //           html = xlsx.utils.sheet_to_html(wb.Sheets[wb.SheetNames[0]]).replace('<table', '<table  class="layui-table" lay-size="sm"')
  //           const id = elem.replace('#', '')
  //           const ele = document.getElementById(id)
  //           ele && (ele.innerHTML = html)
  //           resolve(html)
  //         } else {
  //           wb.SheetNames.forEach((e) => {
  //             'A1' in wb.Sheets[e] && (html += xlsx.utils.sheet_to_html(wb.Sheets[e]).replace('<table', '<table  class="layui-table" lay-size="sm"'))
  //           })
  //           resolve(wb)
  //         }
  //       })
  //     })
  //   }

  /**
   * 文件流接口封装
   * @param url
   * @param params
   */
  getFile(url, params) {
    return new Promise((resolve) => {
      axios(url, {
        responseType: 'arraybuffer',
        params: params,
        headers: { Authorization: getToken() }
      }).then(function (res) {
        resolve(res)
      })
    })
  }
}

export const getToken = () => {
  return 'test';
  // const token = store.get(TOKENNAME)
  // if (!token) {
  //   logout()
  //   return ''
  // }
  // return token.token
}

export const setToken = (value) => {
  // store.set(TOKENNAME, value)
}

export const logout = () => {
  // store.remove(TOKENNAME)
  // store.remove(USERINFO)
  router.push({ name: 'Login' }).catch((e) => e)
}

export const http = Http.getInstance({
  baseURL: config.apiUrl
})
// 对所有请求加上loading
export const setLoading = () =>
  ElLoading.service({
    fullscreen: true,
    lock: true,
    text: '正在加载中...',
    background: 'transparent',
    customClass: 'service-loading'
  })
